package com.crm.system.controller.contractReviewManager;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.ESUtil;
import com.crm.model.entity.common.Dictionary;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.contractManager.CustomerContractQO;
import com.crm.model.qo.contractReviewManager.ContractReviewFormQO;
import com.crm.model.qo.contractReviewManager.ContractReviewQO;
import com.crm.model.vo.cluePoolManager.ClueFollowVO;
import com.crm.model.vo.contractReviewManager.ContractCouponVO;
import com.crm.model.vo.contractReviewManager.ContractReviewDetailVO;
import com.crm.model.vo.contractReviewManager.ContractReviewFormVO;
import com.crm.model.vo.contractReviewManager.ContractReviewResultListVO;
import com.crm.model.vo.customerContractManager.CustomerContractDetailVO;
import com.crm.model.vo.customerContractManager.CustomerContractVO;
import com.crm.model.vo.opportunityManager.OpportunityVO;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.system.service.cluePoolManager.ClueFollowService;
import com.crm.system.service.contractManager.CustomerContractExportService;
import com.crm.system.service.contractManager.CustomerContractService;
import com.crm.system.service.contractReviewManager.ContractReviewService;
import com.crm.system.service.customerManager.CustomerPoolService;
import com.crm.system.service.opportunityManager.OpportunityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author yincuimei
 * @Date 2021/3/30 9:13
 * (客服部)审核管理
 */
@RestController
@RequestMapping("/contractReview")
@Slf4j
public class ContractReviewController {

    @Value("${esurl}")
    public String ESurl;
    @Autowired
    private CustomerDbService customerDbService;
    @Autowired
    private CustomerContractDbService customerContractDbService;
    @Autowired
    private ContractReviewService contractReviewService;
    @Autowired
    private CustomerContractService customerContractService;
    @Autowired
    private ClueFollowService clueFollowService;
    @Autowired
    private OpportunityService opportunityService;
    @Autowired
    private CustomerPoolService customerPoolService;
    @Autowired
    private CustomerContractExportService customerContractExportService;

    /**
     * 审核管理--合同审核列表
     * @author yincuimei
     * @return
     */
    @PostMapping("/selectContractReviewFormList")
    public DataResponse selectContractReviewFormList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                                      @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                                      @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                                      @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                                      ContractReviewFormQO contractReviewFormQO//查询条件
    ){
        DhPageInfo<ContractReviewFormVO> contractReviewFormVODhPageInfo = contractReviewService.selectContractReviewFormVOList(contractReviewFormQO,pageIndex,pageSize,sortName,sortOrder);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),contractReviewFormVODhPageInfo);
    }

    /***
     * @Description:根据合同id获取合同审核信息
     * @Param: contractId 合同id
     * @Author: luojie
     * @Date: 2021/3/30 13:40
     */
    @GetMapping("/getContractReviewDetail")
    public DataResponse getContractReviewDetail(@RequestParam(value="contractId",required = true)String contractId){
        ContractReviewDetailVO contractReviewDetailVO = contractReviewService.getContractReviewDetail(contractId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),contractReviewDetailVO);
    }

    /***
     * @Description: 根据合同id获取合同审核结果List
     * @Param: contractId 合同id
     * @Author: luojie
     * @Date: 2021/3/31 11:44
     */
    @GetMapping("/getContractReviewResultList")
    public DataResponse getContractReviewResultList(@RequestParam(value="contractId",required = true)String contractId,
                                                    @RequestParam(value = "pageIndex", required = true) Integer pageIndex,
                                                    @RequestParam(value = "pageSize", required = true) Integer pageSize){
        DhPageInfo<ContractReviewResultListVO> contractReviewList = contractReviewService.getContractReviewResultList(contractId, pageIndex, pageSize);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),contractReviewList);
    }

    /***
     * @Description: 添加合同审核记录
     * @Param: contractReviewQO 合同审核QO
     * @Author: luojie
     * @Date: 2021/3/31 10:54
     */
    @PostMapping("/addContractReview")
    public DataResponse addContractReview(@RequestBody ContractReviewQO contractReviewQO){
        //查询合同是否已经审核过
        CustomerContractDetailVO customerContractDetailVO = customerContractService.selectCustomerContractVODetail(contractReviewQO.getContractId());
        if("2".equals(customerContractDetailVO.getContractReviewStatus())||"3".equals(customerContractDetailVO.getContractReviewStatus())){
            return new DhResponse(ResponseCodeEnum.CONTRACT_REVIEWED.getResponseCode());
        }

        Boolean result = contractReviewService.addContractReview(contractReviewQO);
        if(result){
            Customer esVo = customerDbService.selectCustomerById(customerContractDetailVO.getCustomerId());
            syncES(esVo,esVo.getAccountId(),"客服审核-普通客户转会员");
            ESUtil.syncConctract(contractReviewQO.getContractId(),ESurl);
            ESUtil.syncOrder(customerContractDetailVO.getOrderId(),ESurl);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }else {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 客服部--合同列表
     * @author yincuimei
     * @return
     */
    @PostMapping("/selectNormalCustomerContractList")
    public DataResponse selectNormalCustomerContractList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                                         @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                                         @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                                         @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                                         CustomerContractQO customerContractQO//查询条件
    ){
        try{
            DhPageInfo<CustomerContractVO> customerProductVOList = customerContractService.selectCustomerContractVOList(customerContractQO,pageIndex,pageSize,sortName,sortOrder,"0");
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerProductVOList);
        }catch(Exception e){
            log.error("合同列表 == customerContract selectNormalCustomerContractList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * (客服部)合同列表--导出合同
     * @param response
     * @param customerContractQO
     * @author yincuimei
     */
    @GetMapping(value="/exportCustomerContract")
    public void exportCustomerContract( HttpServletResponse response,CustomerContractQO customerContractQO){
        //设置类型
        response.setContentType("application/vnd.ms-excel");
        //设置编码
        response.setCharacterEncoding("UTF-8");
        try{
            customerContractExportService.exportCustomerContract(response,customerContractQO);
        }catch (Exception e){
            log.error("contractReview exportCustomerContract error:", e);
        }
    }

    /***
     * @Description:合同审核页面根据跟进记录id查询跟进详情
     * @Param:
     * @Author: luojie
     * @Date: 2021/8/31 8:39
     */
    @RequestMapping("/getFollowRecordDetailById")
    public DataResponse getFollowRecordDetailById(ModelMap model, @RequestParam(value = "followWay", required = false) Integer followWay,
                                             @RequestParam(value = "clueFollowId", required = true) String clueFollowId,
                                             @RequestParam(value = "type", required = false) String type) {
        //跟进详情信息
        ClueFollowVO clueFollowVO = clueFollowService.selectClueFollowVOById(clueFollowId,type,followWay);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),clueFollowVO);
    }

    /***
     * @Description:根据商机id获取商机详情
     * @Param:
     * @Author: luojie
     * @Date: 2021/8/31 8:39
     */
    @RequestMapping("/getOpportunityDetailById")
    public DataResponse getOpportunityDetailById(HttpServletRequest request, ModelMap model, @RequestParam(value = "opportunityId") String opportunityId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        OpportunityVO opportunityVO = opportunityService.opportunityDetail(opportunityId);
        opportunityVO.setOperatorName(userAccount.getUserName());
        //销售阶段  opportunityStatus
        Dictionary dictionary = customerPoolService.selectDictionaryByOne("12", opportunityVO.getOpportunityStatus());
        opportunityVO.setOpportunityStatus(dictionary.getDictName());
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),opportunityVO);
    }

    private void syncES(Customer customer,String accountId,String msg) {

        String token = getToken(accountId,msg);

        Map<String, Object> parMap = transBean2Map(customer);
        parMap.put("authorization",token);
        parMap.put("key",accountId);
        try {
            String result = HttpUtil.post(ESurl+"/cutomer/insertOrUpdate",parMap);
            log.info(ESurl +result +msg);
        } catch (HttpException e) {
            log.info(msg+"ES同步失败");
        }
    }

    private String getToken(String accountId, String msg) {
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("accountId", accountId);
        try {
            return HttpUtil.post(ESurl+"/token/initToken",tokenMap);
        } catch (Exception e) {
            log.info(msg+"获取token失败");
        }
        return null;
    }


    /**
     * 对象装换map
     * @param obj
     * @return
     */
    private static Map<String, Object> transBean2Map(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 得到property对应的getter方法
                Method getter = property.getReadMethod();
                Object value = getter.invoke(obj);
                map.put(key, value);

            }
        } catch (Exception e) {
            System.out.println("transBean2Map Error " + e);
        }
        return map;
    }

    /***
     * @Description: 查询客户下的优惠券
     * @Param: customerId 客户id
     * @Author: baijian
     * @Date: 2021/11/15 10:54
     */
    @PostMapping("/contractCouponList")
    public DataResponse contractCouponList( @RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                            @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                            @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                            @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                            @RequestParam(value = "customerId") String customerId){
        DhPageInfo<ContractCouponVO> list = contractReviewService.contractCouponList(customerId,pageIndex,pageSize,sortName,sortOrder);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),list);

    }


    /**
     * 使用优惠券
     */
    @PostMapping("/couponUse")
    public DataResponse couponUse(@RequestParam(value = "couponId") String couponId,
                                  @RequestParam(value = "couponCode") String couponCode){
        Boolean result = contractReviewService.couponUse(couponId,couponCode);
        if(result){
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }else {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }
}
